<template>
  <div class="user-profile-container">
    <div class="user-profile-header">
      <h2>个人信息</h2>
      <!-- 根据是否有用户信息决定显示添加还是修改按钮 -->
      <div class="header-actions">
        <button 
          v-if="!hasProfileInfo" 
          class="add-info-btn" 
          @click="showEditModal = true"
        >
          添加信息
        </button>
        <button 
          v-else 
          class="edit-info-btn" 
          @click="showEditModal = true"
        >
          修改信息
        </button>
      </div>
    </div>

    <!-- 用户信息展示 -->
    <div class="user-profile-content">
      <div class="profile-section">
        <div class="profile-item">
          <span class="label">头像:</span>
          <div class="avatar-container">
            <img 
              v-if="userProfile.avatar_url" 
              :src="userProfile.avatar_url" 
              alt="用户头像" 
              class="user-avatar"
            >
            <div v-else class="default-avatar">默认头像</div>
          </div>
        </div>

        <div class="profile-item">
          <span class="label">昵称:</span>
          <span class="value">{{ userProfile.nickname || '未设置' }}</span>
        </div>

        <div class="profile-item">
          <span class="label">性别:</span>
          <span class="value">{{ genderMap[userProfile.gender] || '未设置' }}</span>
        </div>

        <div class="profile-item">
          <span class="label">生日:</span>
          <span class="value">{{ userProfile.birthday ? formatDate(userProfile.birthday) : '未设置' }}</span>
        </div>

        <div class="profile-item">
          <span class="label">个性签名:</span>
          <span class="value">{{ userProfile.signature || '未设置' }}</span>
        </div>

        <!-- 用户余额信息 -->
        <div class="profile-item">
          <span class="label">账户余额:</span>
          <span class="value">¥ {{ userBalance }}</span>
        </div>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div class="user-profile-footer">
      <button class="change-password-btn" @click="showPasswordModal = true">修改密码</button>
      <button class="manage-address-btn" @click="manageAddress">收货地址</button>
    </div>

    <!-- 编辑用户信息模态框 -->
    <div v-if="showEditModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <h3>{{ hasProfileInfo ? '修改信息' : '添加信息' }}</h3>
        <form @submit.prevent="saveUserProfile">
          <div class="form-group">
            <label for="nickname">昵称:</label>
            <input 
              type="text" 
              id="nickname" 
              v-model="editForm.nickname" 
              placeholder="请输入昵称"
            >
          </div>

          <div class="form-group">
            <label for="gender">性别:</label>
            <select id="gender" v-model="editForm.gender">
              <option value="0">女</option>
              <option value="1">男</option>
            </select>
          </div>

          <div class="form-group">
            <label for="birthday">生日:</label>
            <input 
              type="date" 
              id="birthday" 
              v-model="editForm.birthday"
            >
          </div>

          <div class="form-group">
            <label for="signature">个性签名:</label>
            <textarea 
              id="signature" 
              v-model="editForm.signature" 
              placeholder="请输入个性签名"
            ></textarea>
          </div>

          <div class="form-group">
            <label for="avatar">头像:</label>
            <input 
              type="file" 
              id="avatar" 
              @change="handleAvatarUpload"
              accept="image/*"
            >
          </div>

          <div class="modal-actions">
            <button type="button" @click="closeModal">取消</button>
            <button type="submit">保存</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 修改密码模态框 -->
    <div v-if="showPasswordModal" class="modal-overlay" @click="closePasswordModal">
      <div class="modal-content" @click.stop>
        <h3>修改密码</h3>
        <form @submit.prevent="changePassword">
          <div class="form-group">
            <label for="currentPassword">当前密码:</label>
            <input 
              type="password" 
              id="currentPassword" 
              v-model="passwordForm.currentPassword" 
              placeholder="请输入当前密码"
              required
            >
          </div>

          <div class="form-group">
            <label for="newPassword">新密码:</label>
            <input 
              type="password" 
              id="newPassword" 
              v-model="passwordForm.newPassword" 
              placeholder="请输入新密码"
              required
            >
          </div>

          <div class="form-group">
            <label for="confirmPassword">确认新密码:</label>
            <input 
              type="password" 
              id="confirmPassword" 
              v-model="passwordForm.confirmPassword" 
              placeholder="请再次输入新密码"
              required
            >
          </div>

          <div v-if="passwordError" class="error-message">
            {{ passwordError }}
          </div>

          <div class="modal-actions">
            <button type="button" @click="closePasswordModal">取消</button>
            <button type="submit" :disabled="passwordLoading">
              {{ passwordLoading ? '修改中...' : '确认修改' }}
            </button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- 收货地址列表模态框 -->
    <div v-if="showAddressModal" class="modal-overlay" @click="closeAddressModal">
      <div class="modal-content address-modal" @click.stop>
        <h3>收货地址</h3>
        <div class="address-list">
          <div 
            v-for="address in userAddresses" 
            :key="address.addressId" 
            class="address-item"
          >
            <div class="address-info">
              <div class="address-header">
                <span class="recipient">{{ address.recipient }}</span>
                <span class="phone">{{ address.phone }}</span>
                <span v-if="address.isDefault" class="default-tag">默认</span>
              </div>
              <div class="address-detail">
                {{ address.province }}{{ address.city }}{{ address.district }}{{ address.detail }}
              </div>
            </div>
            <div class="address-actions">
              <button class="delete-btn" @click="deleteAddress(address.addressId)">删除</button>
            </div>
          </div>
          
          <div v-if="userAddresses.length === 0" class="no-address">
            暂无收货地址
          </div>
        </div>
        
        <div class="modal-actions">
          <button type="button" @click="closeAddressModal">取消</button>
          <button type="button" class="add-address-btn" @click="showAddAddressForm">
            添加收货地址
          </button>
        </div>
      </div>
    </div>
    
    <!-- 添加收货地址模态框 -->
    <div v-if="showAddAddressModal" class="modal-overlay" @click="closeAddAddressModal">
      <div class="modal-content" @click.stop>
        <h3>添加收货地址</h3>
        <form @submit.prevent="addAddress">
          <div class="form-group">
            <label for="recipient">收货人:</label>
            <input 
              type="text" 
              id="recipient" 
              v-model="addressForm.recipient" 
              placeholder="请输入收货人姓名"
              required
            >
          </div>
          
          <div class="form-group">
            <label for="phone">手机号码:</label>
            <input 
              type="text" 
              id="phone" 
              v-model="addressForm.phone" 
              placeholder="请输入手机号码"
              required
            >
          </div>
          
          <div class="form-group">
            <label for="province">所在省份:</label>
            <input 
              type="text" 
              id="province" 
              v-model="addressForm.province" 
              placeholder="请输入省份"
              required
            >
          </div>
          
          <div class="form-group">
            <label for="city">所在城市:</label>
            <input 
              type="text" 
              id="city" 
              v-model="addressForm.city" 
              placeholder="请输入城市"
              required
            >
          </div>
          
          <div class="form-group">
            <label for="district">所在区县:</label>
            <input 
              type="text" 
              id="district" 
              v-model="addressForm.district" 
              placeholder="请输入区县"
              required
            >
          </div>
          
          <div class="form-group">
            <label for="detail">详细地址:</label>
            <textarea 
              id="detail" 
              v-model="addressForm.detail" 
              placeholder="请输入详细地址"
              required
            ></textarea>
          </div>
          
          <div v-if="addressError" class="error-message">
            {{ addressError }}
          </div>
          
          <div class="modal-actions">
            <button type="button" @click="closeAddAddressModal">取消</button>
            <button type="submit" :disabled="addressLoading">
              {{ addressLoading ? '提交中...' : '确认添加' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { getUserProfile, updateUserProfile, updateUserId, updatePassword, getUserAddresses, addUserAddress, getUserBalance } from '@/api';

export default {
  name: 'UserProfile',
  setup() {
    const store = useStore();
    const router = useRouter();
    
    // 用户信息
    const userProfile = ref({
      profileId: null,
      userId: null,
      nickname: '',
      gender: 0,
      birthday: '',
      signature: '',
      avatar_url: ''
    });
    
    // 用户余额
    const userBalance = ref(0);
    
    // 编辑表单
    const editForm = ref({
      nickname: '',
      gender: 0,
      birthday: '',
      signature: '',
      avatarFile: null
    });
    
    // 密码表单
    const passwordForm = ref({
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    });
    
    // 收货地址相关
    const userAddresses = ref([]); // 用户地址列表
    const addressForm = ref({
      recipient: '',
      phone: '',
      province: '',
      city: '',
      district: '',
      detail: ''
    });
    
    // 控制模态框显示
    const showEditModal = ref(false);
    const showPasswordModal = ref(false);
    const showAddressModal = ref(false); // 收货地址列表模态框
    const showAddAddressModal = ref(false); // 添加收货地址模态框
    
    // 状态控制
    const passwordLoading = ref(false);
    const passwordError = ref('');
    const addressLoading = ref(false);
    const addressError = ref('');
    
    // 性别映射 (0-女, 1-男)
    const genderMap = {
      0: '女',
      1: '男'
    };
    
    // 判断是否有用户信息
    const hasProfileInfo = computed(() => {
      return userProfile.value.nickname || 
             userProfile.value.gender || 
             userProfile.value.birthday || 
             userProfile.value.signature;
    });
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN');
    };
    
    // 获取用户信息
    const fetchUserProfile = async () => {
      try {
        const res = await getUserProfile();
        if (res.code === 200 && res.data) {
          userProfile.value = { ...res.data };
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    };
    
    // 获取用户余额
    const fetchUserBalance = async () => {
      try {
        const res = await getUserBalance();
        if (res.code === 200 && res.data) {
          userBalance.value = res.data.balance || 0;
        }
      } catch (error) {
        console.error('获取用户余额失败:', error);
      }
    };
    
    // 处理头像上传
    const handleAvatarUpload = (event) => {
      const file = event.target.files[0];
      if (file) {
        editForm.value.avatarFile = file;
      }
    };
    
    // 关闭编辑模态框
    const closeModal = () => {
      showEditModal.value = false;
    };
    
    // 关闭密码模态框
    const closePasswordModal = () => {
      showPasswordModal.value = false;
      passwordForm.value = {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      };
      passwordError.value = '';
    };
    
    // 关闭地址相关模态框
    const closeAddressModal = () => {
      showAddressModal.value = false;
    };
    
    const closeAddAddressModal = () => {
      showAddAddressModal.value = false;
      // 重置表单
      addressForm.value = {
        recipient: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detail: ''
      };
      addressError.value = '';
    };
    
    // 保存用户信息
    const saveUserProfile = async () => {
      try {
        let res;
        // 根据是否有用户信息决定调用哪个接口
        if (hasProfileInfo.value) {
          // 如果已有用户信息，调用更新接口，发送JSON数据
          const userData = {
            nickname: editForm.value.nickname || '',
            gender: editForm.value.gender || 0,
            birthday: editForm.value.birthday || '',
            signature: editForm.value.signature || ''
          };
          res = await updateUserId(userData);
        } else {
          // 如果没有用户信息，调用添加接口，仍使用FormData（支持文件上传）
          const formData = new FormData();
          formData.append('nickname', editForm.value.nickname || '');
          formData.append('gender', editForm.value.gender || 0);
          formData.append('birthday', editForm.value.birthday || '');
          formData.append('signature', editForm.value.signature || '');
          if (editForm.value.avatarFile) {
            formData.append('avatarFile', editForm.value.avatarFile);
          }
          res = await updateUserProfile(formData);
        }
        
        if (res.code === 200) {
          // 更新成功后重新获取用户信息
          await fetchUserProfile();
          closeModal();
        } else {
          console.error('保存用户信息失败:', res.message);
        }
      } catch (error) {
        console.error('保存用户信息失败:', error);
      }
    };
    
    // 修改密码
    const changePassword = async () => {
      // 重置错误信息
      passwordError.value = '';
      
      // 验证密码一致性
      if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
        passwordError.value = '两次输入的新密码不一致';
        return;
      }
      
      // 验证密码长度
      if (passwordForm.value.newPassword.length < 6) {
        passwordError.value = '新密码长度不能少于6位';
        return;
      }
      
      passwordLoading.value = true;
      
      try {
        // 调用修改密码接口
        const res = await updatePassword({
          username: store.state.user.userinfo.username,
          password: passwordForm.value.currentPassword,
          newPassword: passwordForm.value.newPassword
        });
        
        if (res.code === 200) {
          // 修改成功
          alert('密码修改成功');
          closePasswordModal();
        } else {
          passwordError.value = res.message || '密码修改失败';
        }
      } catch (error) {
        console.error('修改密码失败:', error);
        passwordError.value = '密码修改失败，请稍后重试';
      } finally {
        passwordLoading.value = false;
      }
    };
    
    // 获取用户收货地址列表
    const fetchUserAddresses = async () => {
      try {
        const res = await getUserAddresses();
        if (res.code === 200) {
          userAddresses.value = res.data || [];
        } else {
          console.error('获取收货地址失败:', res.message);
        }
      } catch (error) {
        console.error('获取收货地址失败:', error);
      }
    };
    
    // 管理收货地址
    const manageAddress = async () => {
      // 获取用户收货地址
      await fetchUserAddresses();
      // 显示收货地址列表模态框
      showAddressModal.value = true;
    };
    
    // 显示添加收货地址表单
    const showAddAddressForm = () => {
      closeAddressModal();
      showAddAddressModal.value = true;
    };
    
    // 添加收货地址
    const addAddress = async () => {
      // 重置错误信息
      addressError.value = '';
      
      // 简单验证表单
      if (!addressForm.value.recipient || !addressForm.value.phone || 
          !addressForm.value.province || !addressForm.value.city || 
          !addressForm.value.district || !addressForm.value.detail) {
        addressError.value = '请填写完整的地址信息';
        return;
      }
      
      addressLoading.value = true;
      
      try {
        const res = await addUserAddress(addressForm.value);
        if (res.code === 200) {
          // 添加成功后重新获取地址列表
          await fetchUserAddresses();
          closeAddAddressModal();
          showAddressModal.value = true; // 重新显示地址列表
        } else {
          addressError.value = res.message || '添加地址失败';
        }
      } catch (error) {
        console.error('添加收货地址失败:', error);
        addressError.value = '添加地址失败，请稍后重试';
      } finally {
        addressLoading.value = false;
      }
    };
    
    // 删除收货地址
    const deleteAddress = async (addressId) => {
      if (!confirm('确定要删除这个收货地址吗？')) {
        return;
      }
      
      try {
        // 注意：这里需要根据实际API调整
        const res = await deleteAddress(addressId);
        if (res.code === 200) {
          // 删除成功后重新获取地址列表
          await fetchUserAddresses();
        } else {
          console.error('删除收货地址失败:', res.message);
          alert('删除收货地址失败: ' + res.message);
        }
      } catch (error) {
        console.error('删除收货地址失败:', error);
        alert('删除收货地址失败，请稍后重试');
      }
    };
    
    // 组件挂载时获取用户信息和余额
    onMounted(() => {
      fetchUserProfile();
      fetchUserBalance();
    });
    
    return {
      userProfile,
      userBalance,
      editForm,
      passwordForm,
      userAddresses,
      addressForm,
      showEditModal,
      showPasswordModal,
      showAddressModal,
      showAddAddressModal,
      passwordLoading,
      passwordError,
      addressLoading,
      addressError,
      genderMap,
      hasProfileInfo,
      formatDate,
      handleAvatarUpload,
      closeModal,
      closePasswordModal,
      closeAddressModal,
      closeAddAddressModal,
      saveUserProfile,
      changePassword,
      manageAddress,
      fetchUserAddresses,
      showAddAddressForm,
      addAddress,
      deleteAddress
    };
  }
};
</script>

<style lang="less" scoped>
.user-profile-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  
  .user-profile-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
    
    h2 {
      margin: 0;
      color: #333;
    }
    
    .header-actions {
      button {
        padding: 8px 16px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        
        &.add-info-btn {
          background-color: #409eff;
          color: white;
        }
        
        &.edit-info-btn {
          background-color: #67c23a;
          color: white;
        }
      }
    }
  }
  
  .user-profile-content {
    .profile-section {
      background-color: #f9f9f9;
      border-radius: 8px;
      padding: 20px;
      
      .profile-item {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
        padding: 10px 0;
        border-bottom: 1px solid #eee;
        
        &:last-child {
          border-bottom: none;
        }
        
        .label {
          width: 100px;
          font-weight: bold;
          color: #666;
        }
        
        .value {
          flex: 1;
          color: #333;
        }
        
        .avatar-container {
          .user-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
          }
          
          .default-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background-color: #ddd;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #999;
          }
        }
      }
    }
  }
  
  .user-profile-footer {
    display: flex;
    justify-content: center;
    gap: 20px;
    margin-top: 30px;
    
    button {
      padding: 10px 20px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      
      &.change-password-btn {
        background-color: #409eff;
        color: white;
      }
      
      &.manage-address-btn {
        background-color: #67c23a;
        color: white;
      }
    }
  }
  
  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
  }
  
  .modal-content {
    background-color: white;
    border-radius: 8px;
    padding: 20px;
    width: 90%;
    max-width: 500px;
    max-height: 90vh;
    overflow-y: auto;
    
    h3 {
      margin-top: 0;
      margin-bottom: 20px;
      text-align: center;
    }
    
    .form-group {
      margin-bottom: 15px;
      
      label {
        display: block;
        margin-bottom: 5px;
        font-weight: bold;
      }
      
      input, select, textarea {
        width: 100%;
        padding: 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
        box-sizing: border-box;
      }
      
      textarea {
        min-height: 80px;
        resize: vertical;
      }
    }
    
    .error-message {
      color: #f56c6c;
      margin-bottom: 10px;
      padding: 5px;
      background-color: #fef0f0;
      border-radius: 4px;
    }
    
    .modal-actions {
      display: flex;
      justify-content: center;
      gap: 10px;
      margin-top: 20px;
      
      button {
        padding: 8px 16px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        
        &:first-child {
          background-color: #909399;
          color: white;
        }
        
        &:last-child {
          background-color: #409eff;
          color: white;
        }
        
        &:disabled {
          background-color: #a0cfff;
          cursor: not-allowed;
        }
      }
    }
  }
  
  // 收货地址模态框特殊样式
  .address-modal {
    max-width: 600px;
    
    .address-list {
      max-height: 300px;
      overflow-y: auto;
      margin-bottom: 20px;
      
      .address-item {
        border: 1px solid #eee;
        border-radius: 4px;
        padding: 15px;
        margin-bottom: 10px;
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        
        .address-info {
          flex: 1;
          
          .address-header {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            
            .recipient {
              font-weight: bold;
              margin-right: 15px;
            }
            
            .phone {
              color: #666;
              margin-right: 15px;
            }
            
            .default-tag {
              background-color: #409eff;
              color: white;
              font-size: 12px;
              padding: 2px 6px;
              border-radius: 3px;
            }
          }
          
          .address-detail {
            color: #333;
            line-height: 1.5;
          }
        }
        
        .address-actions {
          .delete-btn {
            background-color: #f56c6c;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
            
            &:hover {
              background-color: #e64a4a;
            }
          }
        }
      }
      
      .no-address {
        text-align: center;
        color: #999;
        padding: 20px;
      }
    }
    
    .add-address-btn {
      background-color: #67c23a !important;
    }
  }
}
</style>
```
